import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Index from '../views/index.vue'
import axios from '../axios'
import store from "../store"

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    children: [
      {
        path: '/index',
        name: 'Index',
        component: Index
      },
      {
        path: '/userCenter',
        name: 'UserCenter',
        meta: {
          title: "个人中心"
        },
        component: () => import('../views/UserCenter.vue')
      },
      // {
      //   path: '/sys/users',
      //   name: 'SysUser',
      //   component: User
      // },
      // {
      //   path: '/sys/roles',
      //   name: 'SysRole',
      //   component: Role
      // },
      // {
      //   path: '/sys/menus',
      //   name: 'SysMenu',
      //   component: Menu
      // },
    ]
  },

  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {

  let hasRoute = store.state.menus.hasRoutes

  let token = localStorage.getItem("token")

  if (to.path == '/login') {

    next()

  } else if (!token) {

    next({ path: '/login' })

  } else if (token && !hasRoute) {

    axios.get('/sys/menu/nav', {
      headers: {
        Authorization: localStorage.getItem('token')
      }
    })
      .then(res => {

        console.log('获得侧边栏菜单');

        let nav = res.data.data.nav;
        let authoritys = res.data.data.authoritys;

        //拿到menuList
        store.commit('setMenuList', nav);
        //拿到用户权限
        store.commit('setPermList', authoritys);

        //动态绑定路由
        let newRoute = router.options.routes;

        nav.forEach(menu => {
          if (menu.children) {
            menu.children.forEach(child => {

              //转成路由
              let route = menuToRoute(child);

              //把路由添加到路由管理中,如果已经存在就不添加
              if (route && newRoute[0].children.findIndex(e => e.path === route.path) == -1) {
                newRoute[0].children.push(route);
              }

            })
          }
        })

        router.matcher = new VueRouter({ mode: 'history' }).matcher;
        router.addRoutes(newRoute);
        let hasRoute = true;
        store.commit('changeRouteStatus', hasRoute);

      });
  }


  next();

})

const menuToRoute = (menu) => {

  if (!menu.component) {
    return null
  }

  let route = {
    name: menu.name,
    path: menu.path,
    meta: {
      icon: menu.icon,
      title: menu.title
    }
  }
  route.component = () => import('@/views/' + menu.component + '.vue')

  return route
}

export default router
